package pwd.allen;

import java.awt.*;
import java.util.List;

public class Missile {
	public static final int XSPEED = 10;
	public static final int YSPEED = 10;

	protected int xSpeed=0,ySpeed=0;
	
	public boolean isGood() {
		return good;
	}

	public static final int WIDTH = 10;
	public static final int HEIGHT = 10;
	int x, y;
	Tank.Direction dir;
	private boolean good;
	protected boolean live = true;
	protected TankClient tc;
	private SpeedUtil speedUtilMove = new SpeedUtil(() -> {move();}, 50);

	public Missile(int x, int y, Tank.Direction dir) {
		super();
		this.x = x;
		this.y = y;
		this.dir = dir;
	}

	public Missile(int x, int y, boolean good, Tank.Direction dir, TankClient tc) {
		this(x, y, dir);
		this.good = good;
		this.tc = tc;
		switch (dir) {
		case L:
			xSpeed=-XSPEED;
			break;
		case LU:
			xSpeed=-XSPEED;
			ySpeed=-YSPEED;
			break;
		case U:
			ySpeed=-YSPEED;
			break;
		case RU:
			xSpeed=XSPEED;
			ySpeed=-YSPEED;
			break;
		case R:
			xSpeed=XSPEED;
			break;
		case RD:
			xSpeed=XSPEED;
			ySpeed=YSPEED;
			break;
		case D:
			ySpeed=YSPEED;
			break;
		case LD:
			xSpeed=-XSPEED;
			ySpeed=YSPEED;
			break;
		}
		if(good==true) {
			xSpeed*=2;
			ySpeed*=2;
		}
	}

	public void draw(Graphics g) {
		if (!live) {
			tc.explodes.add(new Explode(x, y, tc));
			tc.missiles.remove(this);
			return;
		}
		Color c = g.getColor();
		if (this.good)
			g.setColor(Color.BLACK);
		else
			g.setColor(Color.DARK_GRAY);
		g.fillOval(this.x, this.y, WIDTH, HEIGHT);
		g.setColor(c);
		speedUtilMove.run();
	}

	protected void move() {
		x+=xSpeed;
		y+=ySpeed;
		if (x < 5 || y < 24 || x > TankClient.GAME_WIDTH - 3
				|| y > TankClient.GAME_HEIGHT - 3) {
			live = false;
		}
	}

	public boolean isLive() {
		return live;
	}

	public Rectangle getRect() {
		return new Rectangle(x, y, WIDTH, HEIGHT);
	}

	public boolean hitTank(Tank t) {
		if (this.live && t.isLive() && this.getRect().intersects(t.getRect())
				&& this.good != t.isGood()) {
			if (t.isGood()) {
				t.setLife(t.getLife() - 10);
				if (t.getLife() <= 0)
					t.setLive(false);
			} else{
				t.setLife(t.getLife() - 20);
				if (t.getLife() <= 0){
					t.setLive(false);
					tc.hitCount++;
					}
			}
			this.live = false;
			Explode e = new Explode(x, y, tc);
			tc.explodes.add(e);
			return true;
		}
		return false;
	}

	public boolean hitTanks(List<Tank> tanks) {
		for (int i = 0; i < tanks.size(); i++) {
			if (hitTank(tanks.get(i))) {
				return true;
			}
		}
		return false;
	}

	public boolean hitWall(Wall w) {
		if (this.live && this.getRect().intersects(w.getRect())) {
			this.live = false;
			return true;
		}
		return false;
	}
}
